<!-- 遥信管理 -->
<template>
  <div class="">
    <el-card class="head">
      <div style="display: flex">
        <div style="flex: 1">
          <yg-from
            ref="YxForm"
            :formObj="formObj"
            :formData="formData"
            @selectChange="selectChange"
          >
          </yg-from>
        </div>
        <div class="item_button">
          <div>
            <el-button
              type="success"
              size="mini"
              icon="el-icon-search"
              @click="query"
              >查询</el-button
            >
          </div>
          <div>
            <el-button
              type="danger"
              size="mini"
              icon="el-icon-refresh"
              @click="resset"
              >重置</el-button
            >
          </div>
          <div>
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-download"
              @click="exportButton"
              >导出</el-button
            >
          </div>
          <b>
            <el-upload
              action
              ref="upload"
              accept=".xlsx, .xls"
              :show-file-list="false"
              :on-change="handleUpLoad"
              :auto-upload="false"
            >
              <el-button type="primary" size="mini" icon="el-icon-upload2"
                >导入</el-button
              >
            </el-upload>
          </b>
        </div>
      </div>
    </el-card>
    <el-card style="margin-top: 5px">
      <ux-grid
        :data="TableList"
        ref="plxTable"
        stripe
        :border="false"
        max-height="600"
        size="mini"
        :header-cell-style="{ 'text-align': 'center' }"
        style="width: 100%; font-size: 12px"
        v-loading="loadingShow"
        element-loading-text="拼命加载中"
        element-loading-spinner="el-icon-loading"
        :cell-style="handleCellStyle"
        :highlight-current-row="true"
        show-overflow="tooltip"
        widthResize
      >
        <ux-table-column
          v-for="(item, index) in columns"
          :key="index"
          :title="item.label"
          :field="item.prop"
          :align="item.align"
          :width="item.width"
          :formatter="item.formatter"
          resizable
        >
        </ux-table-column>
        <ux-table-column title="操作" width="70">
          <template slot-scope="scope">
            <el-tooltip content="编辑" placement="top" effect="light">
              <el-button
                type="primary"
                icon="el-icon-edit"
                circle
                @click="editYx(scope.row)"
                size="mini"
              ></el-button>
            </el-tooltip>
          </template>
        </ux-table-column>
      </ux-grid>
    </el-card>
    <!-- 修改遥信信息 -->
    <el-dialog
      title="修改遥信"
      :visible.sync="editYxDialogVisible"
      width="50%"
      :close-on-click-modal="false"
    >
      <yg-from
        ref="editYxForm"
        :formObj="editYxFromObj"
        :formData="editYxFromData"
      ></yg-from>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="editYxDialogVisible = false"
          >取 消</el-button
        >
        <el-button size="mini" type="primary" @click="editYxConfirm"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { dataURLtoBlob, getBase64 } from "@/utils/exportExcelBlob/index";
import YgTable from "@/components/Table/YgTable.vue";
import YgFrom from "@/components/Form/YgFrom.vue";
import {
  setMessageCallback,
  publishMsg,
  removeMessageCallback,
  checkSpecialId,
} from "@/mqtt";
export default {
  //import引入的组件需要注入到对象中才能使用
  name: "ParamYX",
  components: {
    YgTable,
    YgFrom,
  },
  data() {
    //这里存放数据
    return {
      editYxDialogVisible: false, //修改遥信信息
      loadingShow: false,
      columns: [
        {
          prop: "id",
          label: "遥信id",
          align: "left",
          width: 200,
        },
        {
          prop: "gw_sn",
          label: "所属网关",
          width: 200,
        },
        {
          prop: "term_key",
          label: "终端Id",
        },
        {
          prop: "name",
          label: "遥信名称",
        },
        {
          prop: "value",
          label: "当前值",
        },
        {
          prop: "update_time",
          label: "刷新时间",
          width: 170,
        },
        {
          prop: "alarm",
          label: "变位告警",
        },
        {
          prop: "alarm_level",
          label: "告警级别",
          formatter({ row }) {
            if (row.hasOwnProperty("alarm_level")) {
              switch (row.alarm_level) {
                case 0:
                  return "无";
                case 1:
                  return "通知";
                case 2:
                  return "一般";
                case 3:
                  return "严重";
                default:
                  return "";
              }
            } else {
              return "";
            }
          },
        },
      ],
      TableList: [],
      formObj: [
        {
          select: true,
          label: "网关名称", //字段
          prop: "gw_sn", //字段名
          placeholder: "请输入出厂编号", //提示内容
          width: 12, //参考el-col
          disabled: false, //是否禁用
          clearable: false, //是否清空
          labelWidth: "80px",
          options: [],
        },
        {
          select: true,
          label: "终端名称", //字段
          prop: "term_key", //字段名
          placeholder: "请输入终端名称", //提示内容
          width: 12, //参考el-col
          disabled: false, //是否禁用
          clearable: false, //是否清空
          labelWidth: "80px",
          options: [{ label: "全选", value: "all" }],
        },
      ],
      formData: {
        gw_sn: "all",
        term_key: "all",
      },
      editYxFromObj: [
        {
          input: true, //是input
          label: "终端名称", //字段
          prop: "id", //字段名
          width: 12, //参考el-col
          placeholder: "请输入终端名称",
          disabled: true, //是否禁用
          labelWidth: "80px",
        },
        {
          input: true, //是input
          label: "遥信名称", //字段
          prop: "name", //字段名
          width: 12, //参考el-col
          placeholder: "请输入遥信名称",
          disabled: false, //是否禁用
          labelWidth: "80px",
          rules: [
            {
              required: true,
              message: "请输入遥信名称",
            },
          ],
        },
        {
          select: true, //是input
          label: "变位告警", //字段
          prop: "alarm", //字段名
          width: 12, //参考el-col
          placeholder: "请输入变位告警",
          disabled: true, //是否禁用
          labelWidth: "80px",
          options: [
            { label: "是", value: 1 },
            { label: "否", value: 0 },
          ],
          // rules: [
          //   {
          //     required: true,
          //     message: "请输入遥信描述",
          //   },
          // ],
        },
        {
          select: true, //是select
          label: "告警级别", //字段
          prop: "alarm_level", //字段名
          width: 12, //参考el-col
          placeholder: "请输入告警级别",
          disabled: false, //是否禁用
          labelWidth: "80px",
          options: [
            { label: "无", value: 0 },
            { label: "通知", value: 1 },
            { label: "一般", value: 2 },
            { label: "严重", value: 3 },
          ],
        },
      ],
      editYxFromData: {
        id: "",
        name: "",
        alarm: "",
        alarm_level: "",
      },
    };
  },
  //监听属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {
    TableList(val, newval) {
      //console.log(val,newval)
    },
  },
  //方法集合
  methods: {
    editYx(val) {
      //console.log("修改遥信信息", val);
      this.editYxDialogVisible = true;
      this.editYxFromData.id = val.id;
      this.editYxFromData.name = val.name;
      this.editYxFromData.alarm = val.alarm;
      this.editYxFromData.alarm_level = Number(val.alarm_level) || "";
    },
    editYxConfirm() {
      if (this.$refs.editYxForm.submitForm()) {
        let newMsg = {
          webMsgType: 1009,
          funCode: 1,
        };
        newMsg.data = this.editYxFromData;
        publishMsg(newMsg);
        this.editYxDialogVisible = false;
      }
    },
    handleCellStyle({ row, column, rowIndex, columnIndex }) {
      if (column.title == "当前值") {
        return { color: "#299cfa", fontWeight: "bold" };
      }
    },
    query() {
      let newMsg = {
        webMsgType: 1009,
        funCode: 0,
      };
      newMsg.data = {
        gw_sn: this.formData.gw_sn,
        term_key: this.formData.term_key,
      };
      publishMsg(newMsg);
      this.loadingShow = true;
    },
    resset() {
      this.$refs.YxForm.resetForm();
    },
    async handleUpLoad(ev) {
      //console.log("ahahhahhhhhhhhhh", ev);
      let file = ev.raw;
      if (!file) return;
      const extension = file.name.substring(file.name.lastIndexOf(".") + 1);
      const fileType = ["xlsx", "xls"].some((item) => item === extension);
      if (!fileType) {
        this.$message.error("格式错误！请选择后缀是.xlsx, .xls 的文件");
        return;
      }
      let res = await getBase64(file);
      let newMsg = {
        webMsgType: 1009,
        funCode: 4,
      };
      newMsg.data = {
        base64_excel: res,
      };
      publishMsg(newMsg);
    },
    exportButton() {
      let newMsg = {
        webMsgType: 1009,
        funCode: 3,
      };
      newMsg.data = {
        gw_sn: this.formData.gw_sn,
        term_key: this.formData.term_key,
      };
      publishMsg(newMsg);
    },
    onMessage(topic, msg) {
      switch (msg.webMsgType) {
        case 1007:
          if (msg.funCode == 0) {
            if (msg.retCode != 0) {
              this.$message.error(msg.retMsg);
            } else {
              let result = msg.data;
              let newArr = this.formObj.filter((v) => {
                return v.prop === "gw_sn";
              });
              newArr[0].options = [];
              result.map((e) => {
                return newArr[0].options.push({
                  label: e.gw_name,
                  value: e.gw_sn,
                });
              });
              const allSelect = { label: "全选", value: "all" };
              newArr[0].options.unshift(allSelect);
            }
          }
          break;
        case 1008:
          if (msg.funCode == 0) {
            if (msg.retCode != 0) {
              this.$message.error(msg.retMsg);
            } else {
              let result = msg.data;
              this.formData.term_key = "all";
              let newArr = this.formObj.filter((v) => {
                return v.prop === "term_key";
              });
              newArr[0].options = [];
              result.map((e) => {
                return newArr[0].options.push({ label: e.name, value: e.id });
              });
            }
          }
          break;
        case 1009:
          {
            switch (msg.funCode) {
              case 0:
                if (msg.retCode != 0 || !msg.data) {
                  this.$message.error(msg.retMsg);
                } else {
                  this.TableList = msg.data;
                  this.loadingShow = false;
                }
                break;
              case 1:
                if (checkSpecialId(msg)) {
                  if (msg.retCode != 0) {
                    this.$message.error(msg.retMsg);
                  } else {
                    this.$message.success("修改信息成功");
                  }
                }
                break;
              case 2:
                if (msg.retCode != 0 || !msg.data) {
                  this.$message.error(msg.retMsg);
                } else {
                  for (let i = 0; i < this.TableList.length; i++) {
                    for (let j = 0; j < msg.data.length; j++) {
                      if (this.TableList[i].id === msg.data[j].id) {
                        this.TableList[i].id = msg.data[j].id;
                        this.TableList[i].value = msg.data[j].value;
                        this.TableList[i].update_time = msg.data[j].update_time;
                      }
                    }
                  }
                }
                break;
              case 3:
                if (checkSpecialId(msg)) {
                  if (msg.retCode != 0) {
                    this.$message.error(msg.retMsg);
                  } else {
                    //console.log(msg.data);
                    let base64Data = msg.data.base64_excel;
                    dataURLtoBlob(base64Data, "遥信数据列表");
                  }
                }
                break;
              case 4:
                if (checkSpecialId(msg)) {
                  if (msg.retCode != 0) {
                    this.$message.error(msg.retMsg);
                  } else {
                    this.$message.success("导入成功");
                  }
                }
                break;
              default:
                break;
            }
          }
          break;
      }
    },
    selectChange(value, index, prop) {
      //console.log(value, index, prop);
      if (prop == "gw_sn") {
        let newArr = this.formObj.filter((v) => {
          return v.prop === "term_key";
        });
        newArr[0].options = [];
        let newMsg = {
          webMsgType: 1008,
          funCode: 0,
        };
        newMsg.data = { gw_sn: value };
        publishMsg(newMsg);
      }
    },
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {},
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    setMessageCallback(this.onMessage);
    //console.log("遥信管理页面请求消息");
    if (sessionStorage.getItem("query_on_page") == 0) {
      // this.$message.warning("请查询列表！！！");
    } else {
      publishMsg({
        webMsgType: 1009,
        funCode: 0,
      });
      this.loadingShow = true;
    }
    publishMsg({
      webMsgType: 1007,
      funCode: 0,
    });
  },
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {
    // setTimeout(() => {
    //   this.Onmessage();
    // }, 200);
  }, //生命周期 - 挂载之前
  destroyed() {
    removeMessageCallback(this.onMessage);
  },
};
</script>
<style lang="scss" scoped>
::v-deep .el-card__body {
  padding: 5px 5px 5px 5px;
}

.item_button {
  width: 400px;
  display: flex;
  margin-top: 1px;

  div {
    margin-left: 20px;
  }
}

@keyframes gradientChange {
  // 0%{opacity: 1;}
  // 100%{opacity: 0;}
  0% {
    color: #193be6;
    font-size: 12px;
  }

  20% {
    color: linear-gradient(
      90deg,
      rgba(65, 118, 211, 0.8) 0%,
      rgba(38, 149, 247, 0.8) 100%
    );
    font-size: 13px;
    font-weight: 600;
  }

  40% {
    color: linear-gradient(
      90deg,
      rgba(65, 118, 211, 0.8) 0%,
      rgba(38, 149, 247, 0.8) 100%
    );
    font-size: 16px;
    font-weight: 600;
  }

  60% {
    color: linear-gradient(
      90deg,
      rgba(65, 118, 211, 0.8) 0%,
      rgba(38, 149, 247, 0.8) 100%
    );
    font-size: 14px;
    font-weight: 600;
  }

  80% {
    color: linear-gradient(
      90deg,
      rgba(65, 118, 211, 0.8) 0%,
      rgba(38, 149, 247, 0.8) 100%
    );
    font-size: 13px;
    font-weight: 600;
  }

  100% {
    color: #1f2025;
    font-size: 12px;
  }
}

.animation-bg {
  animation: gradientChange 1s linear infinite;
}
</style>
